import { defineAsyncComponent, computed, createApp, h } from "vue";


export default {
  mounted(el, binding) {
    
    const loadingComponentName = el.getAttribute("icon")
    const dynamicComponent = computed(() =>
      defineAsyncComponent(() => import(`@/components/loading-icons/LoadingIcon${loadingComponentName}.vue`))
    );
    const customComponent = computed(() =>
      defineAsyncComponent(() => import(`@/components/loading-icons/LoadingCustom.vue`))
    );
    const loadingInstance = createApp({
      render() {
        return h(loadingComponentName>0 ? dynamicComponent.value : customComponent.value);
      }
    });
    const loadingElement = document.createElement('div');
    loadingElement.classList.add('loading-spinner-box');
    loadingInstance.mount(loadingElement);
    loadingElement.style.position = 'absolute';
    loadingElement.style.top = '0';
    loadingElement.style.left = '0';
    loadingElement.style.width = '100%';
    loadingElement.style.height = '100%';
    loadingElement.style.background = '#ffffff';
    loadingElement.style.display = 'flex';
    loadingElement.style.justifyContent = 'center';
    loadingElement.style.alignItems = 'center';
    loadingElement.style.zIndex = '199';
    loadingElement.style.transform = 'translate(0%, 0%)';
    const showLoading = binding.value;
    if (showLoading) {
      el.style.position = 'relative';
      el.appendChild(loadingElement);
    }
    el.__loading__ = loadingElement;
    el.__loading__Show = showLoading;
  },
  updated(el, binding) {
    const loadingElement = el.__loading__;
    const showLoading = binding.value;
    if (showLoading && !el.__loading__Show) {
      el.style.position = 'relative';
      el.appendChild(loadingElement);
      el.__loading__Show = true;
    }else if (!showLoading && el.__loading__Show) {
      el.style.position = '';
      el.removeChild(loadingElement);
      el.__loading__Show = false;
    }
  },
  unmounted(el) {
    if (el.contains(el.loadingElement)) {
      el.removeChild(el.loadingElement);
    }
    el.loadingElement = null;
  }
}